package com.pattern.behavioural.interpretor;

/**
 * @author Ping
 * @date 2022/5/16 15:07
 **/
public class InterpretDemo {

    public static IntExpr build(String input) {
        // 1 * 2 % 3
        IntExpr expr = new MulExpr(new ValueExpr(1),
                               new ModExpr(new ValueExpr(2), new ValueExpr(3)));
        return expr ;
    }
}

/**
 * Define a syntax for expression:
 *  IntExpr ::= Value     # Value
 *           |  IntExpr '*' IntExpr   #MUL
 *           |  IntExpr  '/' IntExpr  #DIV
 *           |  IntExpr '%' IntExpr  #MOD
 */

abstract class IntExpr {
    public abstract int interpret() ;
}

class ValueExpr extends IntExpr {
    private int value ;

    public ValueExpr(int value) {
        this.value = value;
    }

    @Override
    public int interpret() {
        return this.value;
    }
}

class MulExpr extends IntExpr {
    private IntExpr left ;
    private IntExpr right ;

    public MulExpr(IntExpr left, IntExpr right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        return this.left.interpret() * this.right.interpret();
    }
}
class ModExpr extends IntExpr {
    private IntExpr left ;
    private IntExpr right ;

    public ModExpr(IntExpr left, IntExpr right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        return 0;
    }
}